package com.tanhua.sso.service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.common.mapper.UserMapper;
import com.tanhua.common.pojo.User;
import com.tanhua.dubbo.server.api.HuanXinApi;
import com.tanhua.sso.config.AliyunSMSConfig;
import com.tanhua.sso.vo.ErrorResult;
import com.tanhua.sso.vo.LoginResult;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.JwsHeader;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class UserService {


    /*注入mapper*/
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Autowired
    private AliyunSMSConfig aliyunSMSConfig;
    @Value("${jwt.secret}")
    private String secret;
    @Reference(version = "1.0.0")
    private HuanXinApi huanXinApi;



    //发送阿里验证码的方法
//SmsService.java

    /**
     * 发送短信验证码
     *
     * @param mobile
     * @return
     */
    public String sendSms(String mobile) {
        DefaultProfile profile = DefaultProfile.getProfile(this.aliyunSMSConfig.getRegionId(),
                this.aliyunSMSConfig.getAccessKeyId(), this.aliyunSMSConfig.getAccessKeySecret());
        IAcsClient client = new DefaultAcsClient(profile);

        String code = RandomUtils.nextInt(100000, 999999) + "";

        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain(this.aliyunSMSConfig.getDomain());
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");
        request.putQueryParameter("RegionId", this.aliyunSMSConfig.getRegionId());
        request.putQueryParameter("PhoneNumbers", mobile); //目标手机号
        request.putQueryParameter("SignName", this.aliyunSMSConfig.getSignName()); //签名名称
        request.putQueryParameter("TemplateCode", this.aliyunSMSConfig.getTemplateCode()); //短信模板code
        request.putQueryParameter("TemplateParam", "{\"code\":\"" + code + "\"}");//模板中变量替换
        try {
            CommonResponse response = client.getCommonResponse(request);
            String data = response.getData();
            if (StringUtils.contains(data, "\"Message\":\"OK\"")) {
                return code;
            }
            log.info("发送短信验证码失败~ data = " + data);
        } catch (Exception e) {
            log.error("发送短信验证码失败~ mobile = " + mobile, e);
        }
        return null;
    }

    public ErrorResult login(String phone) {
        //设置存储验证码的key
        String redisKey = "CHECK_CODE_" + phone;
        //获取redis中验证码
        String s = redisTemplate.opsForValue().get(redisKey);
        //如果存在，则表示验证还未失效
        if (s != null) {
            return ErrorResult.builder().errCode("666888").errMessage("上次发送的验证码还未失效！！").build();
        }
        //发送验证码：123456
//         String code = sendSms(phone);//固定会返回值
        String code = "123456";
        //根据手机号查询：是否是新用户
        System.out.println("xxxxx" + phone);
        //验证码写入到redis中,有效期为5分钟
        redisTemplate.opsForValue().set(redisKey, code, Duration.ofMinutes(5));
        return null;
    }

    //     * 通过手机号和验证码登录
    public LoginResult userLogin(String phone, String code) {
        //1、获取redis中的验证码
        String redisKey = "CHECK_CODE_" + phone;
        String keyCode = redisTemplate.opsForValue().get(redisKey);
        //2、比较两个验证码
        //2.1 不一致说明验证码错误
        if (!StringUtils.equals(keyCode, code)) {//避免空指针
            log.error("验证码错误！");
            return null;
        }
        //验证码使用之后做删除处理
        redisTemplate.delete(redisKey);
        //设置一个对用户是否为新用户的标识
        Boolean isNew = false;
        //3、通过手机号查询用户信息，判断是否为新用户
        QueryWrapper<User> query = new QueryWrapper<User>();
        //根据手机号查询
        query.eq("mobile", phone);
        User user = userMapper.selectOne(query);
        //4、判断user是否为空
        if (user == null) {//是新用户
            //补充用户信息
            //注册用户信息
            user = new User();
            user.setMobile(phone);
            //给定的初始密码(加密)
            user.setPassword(DigestUtils.md5Hex("123456"));

            //数据保存,保存user
            userMapper.insert(user);

            isNew = true;


            //该用户为新用户,要将环信给赋值上去
//            System.out.println(huanXinApi);
            Boolean result = this.huanXinApi.register(user.getId());
            if (!result) {
                //注册环信失败，记录日志
                log.error("注册环信用户失败~ userId = " + user.getId());
            }
        }
        //TODO 生成token
        //生成token
        Map<String, Object> claims = new HashMap<String, Object>();
        claims.put("id", user.getId());
        claims.put("mobile", phone);//手机号码在token中保存

        Map<String, Object> header = new HashMap<String, Object>();
        header.put(JwsHeader.TYPE, JwsHeader.JWT_TYPE);
        header.put(JwsHeader.ALGORITHM, "HS256");
        String token = Jwts.builder()
                .setHeader(header)
                .setClaims(claims)
//                .signWith(SignatureAlgorithm.ES256, secret)
                .signWith(SignatureAlgorithm.HS256, secret)
                .setExpiration(new Date(System.currentTimeMillis() + 300000))
                .compact();


        // String token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE1NjI4MjkzMzYsInVzZXJfaWQiOiIxIn0.Mbzn6LzsLrkVWEbhexR3lTYDZjxqIcqW11rJxDQ6Ewk";
        return LoginResult.builder().token(token).isNew(isNew).build();
    }


    //做token的校验,返回一个user对象
    //TODO
    public User queryToken(String token) {
        try {
            // 通过token解析数据
            Map<String, Object> body = Jwts.parser()
                    .setSigningKey(secret)
                    .parseClaimsJws(token)
                    .getBody();

            User user = new User();
            user.setId(Long.valueOf(body.get("id").toString()));
            user.setMobile(body.get("mobile").toString());

            return user;
        } catch (ExpiredJwtException e) {
            System.out.println("tokeng过期");
        }catch (Exception e) {
            System.out.println("tokeng不合法");
        }
        return null;
    }
}
